package dao

import (
	"github.com/jinzhu/gorm"
	"time"
)

type OS struct {
	OsId int `json:"os_id" gorm:"column:os_id"`
	Pid int `json:"pid" gorm:"column:pid"`
	Name string `form:"name" json:"name" gorm:"column:name" binding:"required"`
	Desc string `json:"desc" gorm:"column:desc" `
	Status int `json:"status" gorm:"column:status"`
	Ctime int64 `json:"c_time" gorm:"column:c_time"`
	Dtime int64 `json:"d_time" gorm:"column:d_time"`
}
func (t *OS)CreateN(osd *OS) bool {

	bool := true
	osd.Ctime = time.Now().Unix()
	err := db.Create(&osd).Error
	if err != nil {
		bool = false
	}
	return bool

}
func (t *OS)Create(d map[string]interface{}) (bool,int) {

	var osa OS
	if v,ok := d["pid"];ok{
		osa.Pid = v.(int)
	}
	if v,ok := d["name"];ok{
		osa.Name = v.(string)
	}
	if v,ok := d["desc"];ok{
		osa.Desc = v.(string)
	}
	if v,ok := d["status"];ok{
		osa.Status = v.(int)
	}else{
		osa.Status = 1
	}
	//osa.Ctime = time.Now().Format("2006-01-02 15:04:05")

	bool := true
	err := db.Create(&osa).Error
	if err != nil {
		bool = false
	}

	var id []int
	db.Raw("select LAST_INSERT_ID() as id").Pluck("id", &id)
	return bool,id[0]
}
func (t *OS)Delete(os_id int) bool {

	err := db.Where("os_id = ?",os_id).Delete(&t).Error
	b := true
	if err != nil{
		b = false
	}
	return b

}
func (t *OS)Update(os_id int,f map[string]interface{}) bool {

	if v,ok := f["pid"];ok{
		t.Pid = v.(int)
	}
	if v,ok := f["name"];ok{
		t.Name = v.(string)
	}
	if v,ok := f["desc"];ok{
		t.Desc = v.(string)
	}
	if v,ok := f["status"];ok{
		t.Status = v.(int)
	}else{
		t.Status = 1
	}
	err := db.Model(&t).Where("os_id = ?",os_id).Updates(&t).Error
	b := true
	if err != nil {
		b = false
	}
	return b
}
func (t *OS)Find(w map[string]interface{},page int64,pageSize int64) ([]*OS,int,error) {

	var total int = 0
	var os []*OS
	// 获取取指page，指定pagesize的记录
	err := db.Where(w).
		Where("d_time is NULL").
		Limit(pageSize).Offset((page-1)*pageSize).
		Order("os_id desc").
		Find(&os).Error
	if err != nil && err != gorm.ErrRecordNotFound{
		return nil ,0,err
	}

	// 获取总条数
	db.Model(&t).Where(w).Where("d_time is NULL").Count(&total)

	if err != nil && err != gorm.ErrRecordNotFound{
		return nil ,0,err
	}
	return os,total,nil

}
func (t *OS)First(os_id int) (bool,*OS){

	err := db.Where("os_id = ? ",os_id).First(&t).Error
	if err != nil{
		return false,nil
	}
	if t.OsId > 0{
		return true,t
	}
	return false,nil

}

func (t *OS)FirstByName(name string) (bool,*OS){

	err := db.Where("name = ? ",name).First(&t).Error
	if err != nil{
		return false,nil
	}
	if t.OsId > 0{
		return true,t
	}
	return false,nil

}

var OSdao = &OS{}
